package com.ssyc.student.fragment;

import android.app.Dialog;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.MediaPlayerManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.dialog.CustomDialogManager;
import com.ssyc.student.R;
import com.ssyc.student.activity.StudentAddVocabularyDetectionActivity;
import com.ssyc.student.activity.StudentChooseQuestionTypeActivity;
import com.ssyc.student.adapter.StLvVocabularyPrepareAdapter;
import com.ssyc.student.bean.AddVocabularyInfo;
import com.ssyc.student.bean.CommitInfo;
import com.ssyc.student.bean.ResultInfo;
import com.ssyc.student.bean.StAnswerInfo;
import com.ssyc.student.util.RecordTimeUtil;
import com.ssyc.student.util.TimeCount;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--金牌金概念2--题型选择--词汇检测Fragment界面一--听音频或者看单词或者看图片选择答案
 * Created by Administrator on 2018/5/14 0014.
 */

public class StudentAddVocabularyDetectionFragment extends LazyBaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    //课程ID和gradeId
    private String lessonId, gradeId, energy;

    //音频播放
    private ImageView ivPlay;

    //单词
    private TextView tvWrodName;

    //图片
    private ImageView iv;

    //展示选项的列表
    private ListView lv;

    //数据集合
    private List<StAnswerInfo> answerInfos;

    //适配器
    private StLvVocabularyPrepareAdapter adapter;

    //通知Acitvity进行ViewPager翻页的标识
//    public static String VPSCOLL = "StudentVocabularyDetectionFragment.class";

    //当前题目的位置
    private int currPos;

    //所有Question的集合
    private List<AddVocabularyInfo.DataBean.QuestionListBean> question_list;

    //当前页面对象
    private AddVocabularyInfo.DataBean.QuestionListBean info;

    //正确答案
    private String rightAnswer;

    //字母的数组
    private String[] letters;

    //播放录音的网络Url
    private String voiceUrl;
    private AnimationDrawable animationDrawable;

    //通知Activity关闭的标识
    public static final int CLOSE = 0x220;

    //记录当前页面选择答案的位置
    private int chooseAnserPos = -1;

    //弹出是否提交的Dialog
    private Dialog dialog;

    /**
     * 提供的生成当前Fragment的方法
     *
     * @param info 当前页面对象
     * @param pos  当前位置
     * @return
     */
    public static StudentAddVocabularyDetectionFragment newInstance(AddVocabularyInfo.DataBean.QuestionListBean info, int pos, String lessonId, String gradeId, String listJson, String energy) {

        StudentAddVocabularyDetectionFragment studentVocabularyDetectionFragment = new StudentAddVocabularyDetectionFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("data", info);
        bundle.putInt("pos", pos);
        bundle.putString("lessonid", lessonId);
        bundle.putString("gradeid", gradeId);
        bundle.putString("questionjson", listJson);
        bundle.putString("energy", energy);


        studentVocabularyDetectionFragment.setArguments(bundle);

        return studentVocabularyDetectionFragment;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_add_vocabulary_detection;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {

        showContent();

        //初始化视图
        initView(view);

        //模拟数据
        initData();

        //设置ListView的数据
        initLv();
    }

    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        ivPlay = view.findViewById(R.id.iv_play);
        ivPlay.setOnClickListener(this);
        lv = view.findViewById(R.id.lv);
        letters = getResources().getStringArray(R.array.base_letters);
        iv = view.findViewById(R.id.iv);
        tvWrodName = view.findViewById(R.id.tv_name);
    }

    /**
     * 模拟初始数据
     */
    private void initData() {

        //获取lessonId
        lessonId = getArguments().getString("lessonid");

        //获取gradeId
        gradeId = getArguments().getString("gradeid");
        energy = getArguments().getString("energy");

        //获取当前页面的位置
        currPos = getArguments().getInt("pos");

        String questionJson = getArguments().getString("questionjson");
        if (!TextUtils.isEmpty(questionJson)) {
            try {
                question_list = GsonUtil.jsonToList(questionJson, AddVocabularyInfo.DataBean.QuestionListBean[].class);
            } catch (Exception e) {
                Log.i("test", "解析异常");
            }
        }

        //获取当前页面对象
        info = (AddVocabularyInfo.DataBean.QuestionListBean) getArguments().getSerializable("data");

        //设置单词或者图片的显示
        if (!TextUtils.isEmpty(info.getPicture())) {
            //证明是看图选择题
            iv.setVisibility(View.VISIBLE);
            tvWrodName.setVisibility(View.GONE);
            ImageUtil.displayImage(getContext(), iv, info.getPicture());
        }

        if (!TextUtils.isEmpty(info.getWordname())) {
            //证明是文字选择题
            iv.setVisibility(View.GONE);
            tvWrodName.setVisibility(View.VISIBLE);


            //这里如果是文字选择题,需要将填空二字替换成下划红线显示
            tvWrodName.setText(info.getWordname().replace("填空", "____"));
            Log.i("test", "题干："+info.getWordname().replace("填空", "____"));
        }

        //获取正确答案
        rightAnswer = info.getWordpic();

        List<AddVocabularyInfo.DataBean.QuestionListBean.JpglistBean> jpglist = info.getJpglist();
        if (null == jpglist || jpglist.size() == 0) {
            Log.i("test", "返回的Question数据为空");
            return;
        } else {
            answerInfos = new ArrayList<>();
            for (int i = 0; i < jpglist.size(); i++) {
                StAnswerInfo info = new StAnswerInfo();
                info.setAnswerFlag(letters[i]);
                info.setAnswerContent(jpglist.get(i).getText());
                answerInfos.add(info);
            }
        }
    }


    /**
     * 设置ListView的数据
     */
    private void initLv() {
        adapter = new StLvVocabularyPrepareAdapter(getContext(), answerInfos, R.layout.st_lv_vocabulary_detection, rightAnswer);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(this);
    }

    /**
     * 列表条目点击事件
     *
     * @param adapterView
     * @param view
     * @param pos
     * @param l
     */
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        //条目的点击事件
        if (answerInfos.get(pos).isSelect) {
            //表示选择过,点击提示不能再次选择
            UiUtils.Toast("该答案已经选择,不能再次选择", false);
            return;
        } else {
            chooseAnserPos = pos;
            //如果是最后一题,如果选对后则弹框提示完成提交,选错继续
            //如果不是最后一题,选对则发送VP翻页的事件,选错则继续
            if (currPos == StudentAddVocabularyDetectionActivity.getChooseAnswerMap().size() - 1) {
                //最后一个
                //判断选择答案的对错,然后保存到Map中
                if (answerInfos.get(pos).getAnswerContent().replaceAll(" ", "").equals(rightAnswer.replaceAll(" ", ""))) {

                    for (int i = 0; i < answerInfos.size(); i++) {
                        if (answerInfos.get(i).isSelect == false) {
                            answerInfos.get(i).isSelect = true;
                        }
                    }
                    adapter.notifyDataSetChanged();

                    //选择正确后让列表不可在进行交互
                    lv.setEnabled(false);

                    //选择正确
                    StudentAddVocabularyDetectionActivity.getAnswerMap().put(currPos, true);

                    //播放正确的录音
                    doPlayVoiceAction(R.raw.rightmp3, new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mediaPlayer) {
                            // 弹框的操作 ,弹出是否提交的对话框

                        }
                    }, null);

                    showCommitPop();
                } else {
                    //选择错误
                    answerInfos.get(pos).isSelect = true;
                    adapter.notifyDataSetChanged();
                    doPlayVoiceAction(R.raw.errormp3, null, null);
                    StudentAddVocabularyDetectionActivity.getAnswerMap().put(currPos, false);
                }

                //将选择的答案保存到Acitivity的Map中
                StudentAddVocabularyDetectionActivity.getChooseAnswerMap().put(currPos, answerInfos.get(pos).answerFlag);

            } else {
                //不是最后一个
                if (answerInfos.get(pos).getAnswerContent().replaceAll(" ", "").equals(rightAnswer.replaceAll(" ", ""))) {

                    //选对以后全部显示
                    for (int i = 0; i < answerInfos.size(); i++) {
                        if (answerInfos.get(i).isSelect == false) {
                            answerInfos.get(i).isSelect = true;
                        }
                    }

                    adapter.notifyDataSetChanged();

                    //选择正确后让列表不可在进行交互
                    lv.setEnabled(false);

                    //播放正确的录音
                    doPlayVoiceAction(R.raw.rightmp3, null, null);

                    //选择答案后跳转到下一页面,EventBus通知Activity进行ViewPager的翻页操作
                    BusInfo busInfo = new BusInfo();
                    busInfo.vpScoll = StudentAddVocabularyDetectionActivity.VPSCOLL;
                    busInfo.pos = currPos + 1;
                    EventBus.getDefault().post(busInfo);

                    //选择正确
                    StudentAddVocabularyDetectionActivity.getAnswerMap().put(currPos, true);

                } else {
                    //选择错误,继续选择
                    doPlayVoiceAction(R.raw.errormp3, null, null);
                    answerInfos.get(pos).isSelect = true;
                    adapter.notifyDataSetChanged();
                    StudentAddVocabularyDetectionActivity.getAnswerMap().put(currPos, false);
                }

                //将选择的答案保存到Acitivity的Map中
                StudentAddVocabularyDetectionActivity.getChooseAnswerMap().put(currPos, answerInfos.get(pos).answerFlag);
            }
        }
    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && StudentAddVocabularyDetectionActivity.SHOWPOPWINDOW == busInfo.getType()) {
            Map<Integer, String> chooseAnswerMap = StudentAddVocabularyDetectionActivity.getChooseAnswerMap();
            if (currPos == chooseAnswerMap.size() - 1 && !TextUtils.isEmpty(chooseAnswerMap.get(currPos)) && chooseAnserPos != -1 && answerInfos.get(chooseAnserPos).getAnswerContent().replaceAll(" ", "").equals(rightAnswer.replaceAll(" ", ""))) {
                showCommitPop();
            }
        }
    }


    /**
     * 提交的对话框
     */
    private void showCommitPop() {

        dialog = new Dialog(getContext(), R.style.Common_Dialog_theme);

        View view = View.inflate(getContext(), R.layout.st_pop_clean_cach, null);

        //关闭按钮
        ImageView ivClose = view.findViewById(R.id.lv_close);
        ivClose.setVisibility(View.GONE);
        //提示信息
        TextView tvMessage = view.findViewById(R.id.tv_message);
        tvMessage.setText("提交学习记录");
        Button btCommit = view.findViewById(R.id.bt_commit);
        btCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                httpCommit();
            }
        });

        dialog.addContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        dialog.setCancelable(false);//不可取消

        dialog.show();
    }

    /**
     * 提交服务器的操作
     */
    private void httpCommit() {

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }

        CommitInfo commitInfo = new CommitInfo();

        //级别
        commitInfo.setGrade_id(gradeId);
        //课程编号
        commitInfo.setLesson_id(lessonId);
        //模块编号
        commitInfo.setModule_id("18");

        //题目总数量
        commitInfo.setAmount(question_list.size() + "");

        //正确题目数量
        commitInfo.setAmount_t(question_list.size() + "");

        //总分
        commitInfo.setScore("0");

        //得分
        commitInfo.setScore_t("0");

        //获取上传时间
        long useTime = TimeCount.newInstance().getTotalTime() + (System.currentTimeMillis() - TimeCount.newInstance().getLastTime());

        //转化为秒
        String seconds = useTime / 1000 + "";

        commitInfo.setSeconds(seconds);

        List<CommitInfo.SubjectBean> subjectBeans = new ArrayList<>();
        for (int i = 0; i < question_list.size(); i++) {
            CommitInfo.SubjectBean subjectBean = new CommitInfo.SubjectBean();
            //题目编号
            subjectBean.setQuestion_id(question_list.get(i).getTitle() + "");
            //题型编号
            subjectBean.setType_id(question_list.get(i).getTitletype() + "");
            //正确与否
            subjectBean.setResult("1");
            //填空内容
            subjectBean.setContent(question_list.get(i).getWordpic());
            //得分
            subjectBean.setScore("0");
            subjectBeans.add(subjectBean);
        }
        commitInfo.setSubject(subjectBeans);

        //转换成JSON字符串
        String postServerJson = GsonUtil.objectToJson(commitInfo);


        CustomDialogManager.show(getContext(), "提交中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "24");
        map.put("acc", AccountUtils.getAccount(getContext()));
        map.put("role", AccountUtils.getRole(getContext()));
        map.put("studys", postServerJson);
        map.put("apptoken", AccountUtils.getToken(getContext()));
        map.put("platform", "8");
        if (TextUtils.isEmpty(energy)) {
            map.put("energy", "1");
        } else {
            map.put("energy", RecordTimeUtil.energy);
        }

        Log.i("test", "type=24&acc=" + AccountUtils.getAccount(getContext())
                + "&role=" + AccountUtils.getRole(getContext()) + "&studys=" + postServerJson +
                "&apptoken=" + AccountUtils.getToken(getContext()) + "&platform=8" + "&energy=" + energy);

        HttpUtils.post(HttpAdress.COMMITSCORE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                ResultInfo info = null;
                if (!TextUtils.isEmpty(response)) {
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("200".equals(info.state)) {
                            //发送已经做完的更新
                            BusInfo stateInfo = new BusInfo();
                            stateInfo.setType(StudentChooseQuestionTypeActivity.UPDATAPAGESTATE);
                            EventBus.getDefault().post(stateInfo);
                            //上传成功
                            UiUtils.Toast("提交成功", false);
                            //通知宿主Activity界面关闭
                            BusInfo busInfo = new BusInfo();
                            busInfo.setType(CLOSE);
                            EventBus.getDefault().post(busInfo);
                        } else {
                            UiUtils.Toast("提交失败,错误码是:" + info.state, false);
                            Log.i("test", "错误码是:" + info.state);
                        }
                    }
                }
            }
        });


    }

    /**
     * 播放选择正确和错误的音频录音
     *
     * @param resId
     */
    private void doPlayVoiceAction(int resId, MediaPlayer.OnCompletionListener onCompletionListener, MediaPlayer.OnErrorListener onErrorListener) {
        resetIvPlayState();
        MediaPlayerManager.getInstance().playLocalFile(resId, onCompletionListener, onErrorListener);
    }


    /**
     * 播放音频的方法
     */
    private void doPlayAction() {
        //执行帧动画动画
        if (null != animationDrawable && animationDrawable.isRunning()) {
            animationDrawable.stop();
            animationDrawable = null;
            ivPlay.setImageResource(R.drawable.st_voice_big_anim);
        } else {
            animationDrawable = (AnimationDrawable) ivPlay.getDrawable();
            animationDrawable.start();
        }

        MediaPlayerManager.getInstance().play(info.getSound(), new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                resetIvPlayState();
            }
        }, new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
                resetIvPlayState();
                return false;
            }
        });
    }

    /**
     * 停止帧动画,重新设置播放按钮的状态
     */
    private void resetIvPlayState() {
        if (null != animationDrawable && animationDrawable.isRunning()) {
            animationDrawable.stop();
            animationDrawable = null;
            ivPlay.setImageResource(R.drawable.st_voice_big_anim);
        }
    }


    /**
     * 对用户不可见的时候停止播放音频
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isVisibleToUser) {
            resetIvPlayState();
            MediaPlayerManager.getInstance().stop();
        }
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_play) {
            //播放音频
            doPlayAction();
        }
    }


}
